package com.fary.web.servlet.mvc.method.annotation;

import com.fary.core.MethodParameter;
import com.fary.util.PatternMatchUtils;
import com.fary.web.context.request.NativeWebRequest;
import com.fary.web.method.support.HandlerMethodReturnValueHandler;
import com.fary.web.method.support.ModelAndViewContainer;

public class ViewNameMethodReturnValueHandler implements HandlerMethodReturnValueHandler {

    private String[] redirectPatterns;


    /**
     * Configure one more simple patterns (as described in {@link PatternMatchUtils#simpleMatch})
     * to use in order to recognize custom redirect prefixes in addition to "redirect:".
     * <p>Note that simply configuring this property will not make a custom redirect prefix work.
     * There must be a custom View that recognizes the prefix as well.
     *
     * @since 4.1
     */
    public void setRedirectPatterns(String... redirectPatterns) {
        this.redirectPatterns = redirectPatterns;
    }

    /**
     * The configured redirect patterns, if any.
     */
    public String[] getRedirectPatterns() {
        return this.redirectPatterns;
    }


    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        Class<?> paramType = returnType.getParameterType();
        return (void.class == paramType || CharSequence.class.isAssignableFrom(paramType));
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType,
                                  ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

        String viewName = returnValue.toString();
        mavContainer.setViewName(viewName);
        if (isRedirectViewName(viewName)) {
            mavContainer.setRedirectModelScenario(true);
        }
    }

    protected boolean isRedirectViewName(String viewName) {
        return (PatternMatchUtils.simpleMatch(this.redirectPatterns, viewName) || viewName.startsWith("redirect:"));
    }

}